﻿using System;
using System.Linq;
using Gp.Scripts.Core;
using Gp.Scripts.GameLogic;
using Pathfinding;
using QFramework;
using Sirenix.OdinInspector;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;

namespace Gp.Scripts.Editor
{
    [Serializable]
    public class SettleMainNode
    {
        private SettleEditor _editor;

        [FoldoutGroup("Character")]
        [HideLabel]
        [SerializeField] private EntityConfigInfo info;

        [FoldoutGroup("Character")]
        [LabelText("尽可能生成在网格上")]
        [SerializeField] private bool spawnOnGrid;
        

        public SettleMainNode(SettleEditor editor)
        {
            _editor = editor;
        }


        [FoldoutGroup("Character")]
        [Button("生成角色", ButtonSizes.Large)]
        private void BuildCharacter()
        {
            if (!info.ValidateInfo())
            {
                _editor.ShowNotification(new GUIContent("角色信息有误"));
                return;
            }
            
            GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(PathConst.HUMANOID_CHARACTER_TEMPLATE);
            var instance = prefab.Instantiate();
            Undo.RegisterCreatedObjectUndo(instance, "Create Character");
            EditorCommonUtils.CreateObjectInScene(instance);
            instance.transform.SetParent(SceneRoot.Get<CharacterRoot>().transform);
            
            if (instance.TryGetComponent<EntityBehaviour>(out var entityBehaviour))
            {
                entityBehaviour.SetEditorConfig(info);
                entityBehaviour.EditorLoadModel();
            }
            
            
            if (spawnOnGrid && AstarPath.active)
            {
                TryInitAStarPath();
                AstarPath.active.Scan();
                var nnInfo = AstarPath.active.GetNearest(instance.transform.position, NNConstraint.Default);
                instance.transform.position = (Vector3) nnInfo.node.position;
            }

            entityBehaviour.name = info.name;
            
            entityBehaviour.SetAllLayer(LayerEnum.BattleCharacter.ToLayerInt());
            entityBehaviour.RebuildGuid();
        }


        [Button("重新生成所有角色 GUID")]
        private void RefreshAllGuid()
        {
            var guids = Global.GetSceneRoot<CharacterRoot>().GetComponentsInChildren<EntityBehaviour>(true);
            if (!EditorUtility.DisplayDialog("重新生成GUID", $"确定重新生成所有角色GUID？（共 {guids.Length} 个对象） ", "ok"))
            {
                return;
            }
            Undo.RecordObjects(guids.Select(x => x as Object).ToArray(), "生成GUID");
            foreach (var guid in guids)
            {
                guid.RebuildGuid();
                EditorUtility.SetDirty(guid);
            }
        } 

        private void TryInitAStarPath()
        {
            if (AstarPath.active.graphs is not {Length: > 0} )
                AstarPath.active.data.Awake();
        } 
        

        // [FoldoutGroup("Trigger")]
        // [Button("生成触发器", ButtonSizes.Large)]
        // private void BuildTrigger() { }
    }
}